<?php

namespace common\models;

use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "package_uploaded_excel".
 *
 * @property string $id
 * @property string $file_name
 * @property string $file_save_name
 * @property integer $imported
 * @property string $owner
 * @property string $package_id
 * @property string $created_at
 */
class PackageUploadedExcel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_uploaded_excel';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['file_name', 'file_save_name', 'owner', 'package_id'], 'required'],
            [['imported', 'owner', 'package_id'], 'integer'],
            [['created_at'], 'safe'],
            [['file_name', 'file_save_name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'file_name' => '文件名称',
            'file_save_name' => '存储名称',
            'imported' => '是否入库',
            'owner' => '上传人',
            'package_id' => '资产包',
            'created_at' => '上传时间',
        ];
    }

    /**
     * 上传成功后保存日志
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if ($insert) {
            $packageLog = new PackageLog();
            $packageLog->package_id = $this->package_id;
            $packageLog->created_at = date('Y-m-d H:i:s');
            $packageLog->user_id = $this->owner;
            $packageLog->log = "导入excel【{$this->file_name}】";
            $re = $packageLog->save();
            if (!$re) {
                throw new Exception("上传Excel【{$this->file_name}】记录保存失败");
            }
        }
    }

    public function afterDelete()
    {
        parent::afterDelete(); // TODO: Change the autogenerated stub

        $packageLog = new PackageLog();
        $packageLog->package_id = $this->package_id;
        $packageLog->created_at = date('Y-m-d H:i:s');
        $packageLog->user_id = Yii::$app->user->id;
        $packageLog->log = "删除Excel【{$this->file_name}】";
        $re = $packageLog->save();
        if (!$re) {
            throw new Exception("删除Excel【{$this->file_name}】记录保存失败");
        }
    }

}
